import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getUserList, getUserById, toggleUserStatus } from '@/api/user'

const initialState = {
  userList: [],
  currentUser: null,
  total: 0,
  loading: false,
  error: null,
}

// 获取小程序用户列表
export const fetchUserList = createAsyncThunk(
  'appUser/fetchUserList',
  async ({ page = 1, size = 10 }, { rejectWithValue }) => {
    try {
      const data = await getUserList(page, size)
      return data
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 获取用户详情
export const fetchUserById = createAsyncThunk(
  'appUser/fetchUserById',
  async (id, { rejectWithValue }) => {
    try {
      const data = await getUserById(id)
      return data
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 切换用户状态（启用/禁用）
export const changeUserStatus = createAsyncThunk(
  'appUser/changeUserStatus',
  async ({ id, status }, { rejectWithValue }) => {
    try {
      const data = await toggleUserStatus(id, status)
      return { id, status, data }
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

const appUserSlice = createSlice({
  name: 'appUser',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null
    },
    clearCurrentUser: (state) => {
      state.currentUser = null
    },
  },
  extraReducers: (builder) => {
    builder
      // 获取用户列表
      .addCase(fetchUserList.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchUserList.fulfilled, (state, action) => {
        state.loading = false
        // 如果是数组，直接使用；如果是对象，取data字段
        if (Array.isArray(action.payload)) {
          state.userList = action.payload
          state.total = action.payload.length
        } else {
          state.userList = action.payload.data || action.payload.list || []
          state.total = action.payload.total || action.payload.size || 0
        }
      })
      .addCase(fetchUserList.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload
      })
      // 获取用户详情
      .addCase(fetchUserById.pending, (state) => {
        state.loading = true
      })
      .addCase(fetchUserById.fulfilled, (state, action) => {
        state.loading = false
        state.currentUser = action.payload.data || action.payload
      })
      .addCase(fetchUserById.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload
      })
      // 切换用户状态
      .addCase(changeUserStatus.fulfilled, (state, action) => {
        const user = state.userList.find((item) => item.id === action.payload.id)
        if (user) {
          user.status = action.payload.status
        }
      })
  },
})

export const { clearError, clearCurrentUser } = appUserSlice.actions
export default appUserSlice.reducer

